frontend/pages/api/nauth/[...nextauth].js (view raw)
1import NextAuth from 'next-auth';
2import CredentialsProvider from 'next-auth/providers/credentials';
3import GoogleProvider from 'next-auth/providers/google';
4
5const {STRAPI_URL = 'http://localhost:1337'} = process.env;
6
7const authHandler = NextAuth({
8 providers: [
9 CredentialsProvider({
10 name: 'Strapi',
11 credentials: {
12 email: {label: 'Email', type: 'text'},
13 password: {label: 'Password', type: 'password'},
14 },
15 async authorize(credentials, req) {
16 const response = await fetch(`${STRAPI_URL}/api/auth/local`, {
17 method: 'POST',
18 headers: {'Content-Type': 'application/json'},
19 body: JSON.stringify({
20 identifier: credentials.email,
21 password: credentials.password,
22 }),
23 });
24 const data = await response.json();
25 if (data?.error?.message === 'Your account email is not confirmed')
26 throw new Error('EmailNotConfirmed');
27 else if (!data?.jwt) return null;
28 else {
29 const {user, jwt} = data;
30 return {...user, jwt};
31 }
32 },
33 }),
34 GoogleProvider({
35 clientId: process.env.GOOGLE_CLIENT_ID,
36 clientSecret: process.env.GOOGLE_CLIENT_SECRET,
37 }),
38 ],
39 session: {
40 jwt: true,
41 },
42 callbacks: {
43 jwt: async params => {
44 const {token, user, account} = params;
45
46 // Google Auth
47 if (account?.provider === 'google') {
48 const response = await fetch(
49 `${STRAPI_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
50 );
51 const data = await response.json();
52
53 if (data.error) {
54 console.error(
55 `Error from Strapi on authentication with Google: `,
56 data.error
57 );
58 throw new Error(data.error?.message || data.error);
59 }
60
61 token.id = data.user.id;
62 token.jwt = data.jwt;
63 token.email = data.user.email;
64 token.username = data.user.name;
65 token.lang = data.user.lang?.toLowerCase();
66 token.provider = account.provider;
67 }
68
69 // Strapi Auth
70 else if (user) {
71 token.id = user.id;
72 token.jwt = user.jwt;
73 token.email = user.email;
74 token.username = user.firstname;
75 token.lang = user.lang?.toLowerCase();
76 token.provider = account.provider;
77 }
78
79 return token;
80 },
81 session: async params => {
82 const {session, token} = params;
83 if (session) {
84 try {
85 const response = await fetch(`${STRAPI_URL}/api/users/me`, {
86 headers: {
87 'Content-Type': 'application/json',
88 Authorization: `Bearer ${token.jwt}`,
89 },
90 });
91 const profile = await response.json();
92 session.profile = profile;
93 } catch (error) {
94 console.error(error);
95 }
96
97 session.token = token;
98 session.user.name = token.username;
99 session.user.lang = token.lang;
100 }
101 return session;
102 },
103 },
104 pages: {
105 signIn: '/auth/login',
106 error: '/auth/login',
107 },
108});
109
110export default async function handler(...params) {
111 await authHandler(...params);
112}